import matplotlib.pyplot as plt 
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
import numpy as np

# load data
digits = load_digits()

# # plot the digits
# fig = plt.figure(figsize=(6, 6))  # figure size in inches
# fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)

# # plot the digits: each image is 8x8 pixels
# for i in range(64):
#     ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[])	#xtricks每个图片的坐标
#     ax.imshow(digits.images[i], cmap=plt.cm.binary)
    
#     # label the image with the target value
#     ax.text(0, 7, str(digits.target[i]))

# plt.show()
N = len(digits.target)
# print(N)
_digits = [0]*N

for i in range(len(digits.images)):
	_digits[i] = digits.images[i].flatten()



train = _digits[:int(0.95*N)]
y_train = digits.target[:int(0.95*N)]
# print(type(train), train)
# print(int(0.95*N))
test = _digits[int(0.95*N):]	#test里面又90个数据
y_test = digits.target[int(0.95*N):]

clf = LogisticRegression(penalty='l1', C=1.0, random_state=0)
clf.fit(train, y_train)
y_pred = clf.predict(test)
print('prob:', y_pred)
print('real:', y_test)
# y_test = y_test.reshape(1, -1)
print('正确率:', clf.score(test,y_test))

###############错误样本的可视化###################
# plot the digits
fig = plt.figure('bad consequences') # figure size in inches
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)


record = [[] for i in range(3)]

# 计算错误的张数

for i in range(len(y_test)):
	if y_pred[i] != y_test[i]:
		record[0].append(digits.images[int(0.95*N)+i].reshape(8, 8))
		record[1].append(y_pred[i])
		record[2].append(y_test[i])

# plot the digits: each image is 8x8 pixels
for i in range(len(record[1])):
    ax = fig.add_subplot(int(len(record[1]))/2+1, 2, i + 1, xticks=[], yticks=[])	#xtricks每个图片的坐标
    ax.imshow(record[0][i], cmap=plt.cm.binary)
    
    # label the image with the target value
    ax.text(0, 4, 'r:'+str(record[2][i]))	#real
    ax.text(0, 7, 'p:'+str(record[1][i]))	#prob

plt.show()
